package hardware;

import java.util.Arrays;
import java.util.Random;

public class BranchPrediction {
    /**
     * http://ifeve.com/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array/
     * 分支预测
     */
    public static void main(String[] args) {
        int[] arr = new int[50000];
        Random rnd = new Random(0);
        for (int i = 0; i < arr.length; i++) {
            arr[i] = rnd.nextInt(256);
        }
        int[] sortArr = Arrays.copyOf(arr, arr.length);
        long start = System.currentTimeMillis();
        Arrays.sort(sortArr);
        System.out.println("排序时间"+(System.currentTimeMillis()-start));
        test(arr, 1);
        test(sortArr, 1);
    }

    public static void test(int[] arr, int loopTime) {
        long sum = 0;
        long start = System.currentTimeMillis();
        for (int x = 0; x < loopTime; x++) {
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] >= 128) {
                    sum += arr[i];
                }
            }
        }
        long end = System.currentTimeMillis();
//        System.out.println("用时：" + (end - start) );
        System.out.println("用时：" + (end - start) + " 结果：" + sum);
    }

}
